package service

import (
	"context"
	"strconv"
	"time"

	"gitee.com/jiebaiyou/formflow/internal/tokenutil"
	"gitee.com/jiebaiyou/formflow/model"
)

// refreshTokenService 实现了model.RefreshTokenService接口, 提供刷新令牌相关的业务逻辑
// 包括用户查询和令牌生成功能
type refreshTokenService struct {
	userRepository model.UserRepository
	contextTimeout time.Duration
}

// NewRefreshTokenService 创建并返回一个实现了model.RefreshTokenService接口的实例
func NewRefreshTokenService(userRepository model.UserRepository, timeout time.Duration) model.RefreshTokenService {
	return &refreshTokenService{
		userRepository: userRepository,
		contextTimeout: timeout,
	}
}

// GetUserByID 根据用户ID查询用户信息
func (rtu *refreshTokenService) GetUserByID(c context.Context, id string) (model.User, error) {
	ctx, cancel := context.WithTimeout(c, rtu.contextTimeout)
	defer cancel()

	// 将字符串ID转换为uint
	idUint, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		return model.User{}, err
	}

	return rtu.userRepository.GetByID(ctx, uint(idUint))
}

// CreateAccessToken 为用户创建访问令牌(JWT)
func (rtu *refreshTokenService) CreateAccessToken(user *model.User, secret string, expiry int) (accessToken string, err error) {
	return tokenutil.CreateAccessToken(user, secret, expiry)
}

// CreateRefreshToken 为用户创建刷新令牌(JWT)
func (rtu *refreshTokenService) CreateRefreshToken(user *model.User, secret string, expiry int) (refreshToken string, err error) {
	return tokenutil.CreateRefreshToken(user, secret, expiry)
}

// ExtractIDFromToken 从请求令牌中提取用户ID
func (rtu *refreshTokenService) ExtractIDFromToken(requestToken string, secret string) (string, error) {
	return tokenutil.ExtractIDFromToken(requestToken, secret)
}
